package me.leiusual.sharing.ui.mine.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.UserMessage

/**
 * author: leiusual
 * create on: 2019-08-04
 * description:
 */
class MineMessageAdapter(
    private val bindListener: (UserMessage) -> Unit
) : PagedListAdapter<UserMessage, MineMessageViewHolder>(DIFF_CALLBACK) {

  companion object {
    private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<UserMessage>() {
      override fun areItemsTheSame(oldItem: UserMessage, newItem: UserMessage): Boolean {
        return oldItem.id == newItem.id
      }

      override fun areContentsTheSame(oldItem: UserMessage, newItem: UserMessage): Boolean {
        return oldItem == newItem
      }
    }
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MineMessageViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val itemView = inflater.inflate(R.layout.view_holder_mine_message, parent, false)
    return MineMessageViewHolder(itemView)
  }

  override fun onBindViewHolder(holder: MineMessageViewHolder, position: Int) {
    val userMessage = getItem(position) ?: return
    holder.bind(userMessage)

    // 用于去触发 已读更新
    if (!userMessage.viewed) {
      bindListener(userMessage)
    }
  }
}